package com.ruoyi.riskrule.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.bizsys.domain.*;
import com.ruoyi.bizsys.service.*;
import com.ruoyi.bizsys.utils.BizConstants;
import com.ruoyi.common.constant.RiskConstants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.enums.RspEnmu;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.Func;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.riskrule.config.common.RuleUtils;
import com.ruoyi.riskrule.constants.Constants;
import com.ruoyi.riskrule.domain.RuleInNextStepCrs;
import com.ruoyi.riskrule.domain.RuleInNextStepXds;
import com.ruoyi.riskrule.domain.RuleNextDto;
import com.ruoyi.riskrule.service.ICreditFieldService;
import com.ruoyi.riskrule.service.IRiskCustomerService;
import com.ruoyi.riskrule.service.ILoanFieldService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author mac
 */
@Slf4j
@Configuration
@AllArgsConstructor
public class Step2ParamsLoader {

    private ILoanOrderService loanOrderService;

    private ICreditApplyService creditApplyService;

    private IRealNameAuthService realNameAuthService;

    private ILoanFieldService loanService;

    private IRiskCustomerService customerService;

    private ICreditAccountService creditAccountService;

    private IAppUserService appUserService;

    private ICreditFieldService creditService;

    private ICustomerInfoService customerInfoService;

    public Object initRuleInParam(RuleNextDto ruleNextDTO, String tkType, String tkKey, String token, String entryId) {
        RuleInNextStep ruleInNextStep = new RuleInNextStep();
        CustomerXdsReport ctcustomerXdsReport = null;
        CustomerCrsReport ctcustomerCrsReport = null;

        ruleInNextStep.setLasttimereport(Constants.DEFAULT_TIME);
        //征信数据类型 未查得=-1，XDS查得=0，CRS查得=1
        String reporttype = "-1";

        //xds 或 crs 报告
        Object report = ruleNextDTO.getCreditReport();
        if (report instanceof CustomerXdsReport) {
            ctcustomerXdsReport = (CustomerXdsReport) report;
            ruleInNextStep.setLasttimereport(DateUtils.formatDate(ctcustomerXdsReport.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            reporttype = "0";
        }

        if (report instanceof CustomerCrsReport) {
            ctcustomerCrsReport = (CustomerCrsReport) report;
            ruleInNextStep.setLasttimereport(DateUtils.formatDate(ctcustomerCrsReport.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            reporttype = "1";
        }

        ruleInNextStep.setReporttype(reporttype);
        ruleInNextStep.setReportchecked(ruleNextDTO.getReportChecked());

        ruleInNextStep.setEntryId(entryId);
        ruleInNextStep.setToken(token);

        //1授信2提现
        if (RiskConstants.RULE_TYPE_APPLY.equals(tkType)) {
            ruleInNextStep.setOperType("3");
            //ruleIn.setWorkflowCode(ruleConfig.RULE_WORK_FLOW_CODE_CREDIT);

            //申请信息查询条件
            CreditApply creditApply = new CreditApply();
            creditApply.setState(UserConstants.BUSINESS_NORMAL);
            creditApply.setApplySerialNo(tkKey);
            List<CreditApply> creditApplyList = creditApplyService.selectCreditApplyList(creditApply);
            if (CollectionUtils.isEmpty(creditApplyList)) {
                throw new BusinessException(RspEnmu.NO_RECORD);
            }
            creditApply = creditApplyList.get(0);

            ruleInNextStep.setReligion(creditApply.getReligion());
            ruleInNextStep.setApplySerialNo(creditApply.getApplySerialNo());
            ruleInNextStep.setCustNo(creditApply.getCustNo());

            //通讯录关联客户数
            if (Func.isNotEmpty(creditApply.getRelatePhone())) {
                ruleInNextStep.setCntcontact1(creditService.getCntcontactRelation(creditApply.getRelatePhone()));
            }
            if (Func.isNotEmpty(creditApply.getRelatePhone2())) {
                ruleInNextStep.setCntcontact2(creditService.getCntcontactRelation(creditApply.getRelatePhone2()));
            }

        } else if (RiskConstants.RULE_TYPE_LOAN.equals(tkType)) {
            ruleInNextStep.setOperType("4");
            //ruleIn.setWorkflowCode(ruleConfig.RULE_WORK_FLOW_CODE_LOAN);

            //提现借据信息
            LoanOrder loanOrder = new LoanOrder();
            loanOrder.setLoanSerialNo(tkKey);
            loanOrder.setState(UserConstants.BUSINESS_NORMAL);
            List<LoanOrder> loanOrderList = loanOrderService.selectLoanOrderList(loanOrder);
            if (CollectionUtils.isEmpty(loanOrderList)) {
                throw new BusinessException(RspEnmu.NO_RECORD);
            }
            loanOrder = loanOrderList.get(0);

            ruleInNextStep.setLoanSerialNo(loanOrder.getLoanSerialNo());
            ruleInNextStep.setCustNo(loanOrder.getCustNo());

            CreditApply creditApply = new CreditApply();
            creditApply.setCustNo(loanOrder.getCustNo());
            creditApply.setApplyStatus(Constants.APPLY_STATUS_1_PASSED);
            creditApply.setState(UserConstants.BUSINESS_NORMAL);

            List<CreditApply> creditApplyList = creditApplyService.selectCreditApplyList(creditApply);
            if (CollectionUtils.isEmpty(creditApplyList)) {
                throw new BusinessException(RspEnmu.NO_RECORD);
            }

            ruleInNextStep.setApplySerialNo(creditApplyList.get(0).getApplySerialNo());
            //当前申请提现金额
            ruleInNextStep.setCurrentapplyline(loanOrder.getLoanAmt() == null ? "0" : loanOrder.getLoanAmt().toString());
            //当前申请提现选择产品的天数
            ruleInNextStep.setCurrentapplyperiod(loanOrder.getPeriodNum() + "");

            Integer[] statusArr = new Integer[2];
            statusArr[0] = 1;
            //当前申请人结清合同数
            ruleInNextStep.setJieqinghetongshu(loanService.selectContractsByStatus(loanOrder.getCustNo(), statusArr, null) + "");

            //征信有效期
            ruleInNextStep.setExpiryDate(customerService.getExpiryDateByUserId(creditApplyList.get(0).getUserId()));

            //授信额度
            CreditAccount creditAccount = getCreditAccount(loanOrder.getCustNo());
            ruleInNextStep.setCreditLine(creditAccount.getCreditLine() + "");

            //Creditused
            BigDecimal add = loanOrder.getLoanAmt().add(creditAccount.getLoanQuota());
            ruleInNextStep.setCreditused(add.divide(creditAccount.getCreditLine(), BigDecimal.ROUND_HALF_UP) + "");


            // 当笔利息
            ruleInNextStep.setCurrentinterest(loanOrder.getInterestAmt().toString());
            // 当笔服务费
            ruleInNextStep.setCurrentservicefee(loanOrder.getServiceFee().toString());

            //信用评级
            CustomerInfo customerInfo = customerInfoService.getOne(new QueryWrapper<CustomerInfo>().eq("cust_no",loanOrder.getCustNo()));
            ruleInNextStep.setCustrating(customerInfo.getCreditRating());

        } else {
            throw new BusinessException(RspEnmu.NO_RECORD);
        }

        RealNameAuth realNameAuth = new RealNameAuth();
        realNameAuth.setCustNo(ruleInNextStep.getCustNo());
        realNameAuth.setState(UserConstants.BUSINESS_NORMAL);
        List<RealNameAuth> realNameAuths = realNameAuthService.selectRealNameAuthList(realNameAuth);
        realNameAuth = realNameAuths.get(0);
        Map<String, Integer> ageDetail = DateUtils.getAgeDetailByddmmyyyy(realNameAuths.get(0).getBirthDate());
        ruleInNextStep.setApplyAge(ageDetail.get("year") + "");
        //BVN
        ruleInNextStep.setBvnNumber(realNameAuths.get(0).getBvnAccount());

        AppUser appUser = new AppUser();
        appUser.setUserUuid(realNameAuth.getUserId());
        appUser = appUserService.selectAppUserList(appUser).get(0);
        //渠道
        ruleInNextStep.setChannel(appUser.getChannel());
        //crs 批次
        ruleInNextStep.setStageResult(StringUtils.isEmpty(appUser.getStageResult()) ? "-1" :appUser.getStageResult());

        if (Func.isNotEmpty(appUser.getRecommendCode())) {
            AppUser inviteUser = new AppUser();
            inviteUser.setInviteCode(appUser.getRecommendCode());
            inviteUser.setInviteCodeStatus("1");
            List<AppUser> inviteUserList = appUserService.selectAppUserList(inviteUser);
            ruleInNextStep.setInvitedbynet(inviteUserList.size() > 0 ? "1" : "0");
        }

        CreditApply creditApply = new CreditApply();
        creditApply.setApplySerialNo(tkKey);
        List<CreditApply> creditApplyList = creditApplyService.selectCreditApplyList(creditApply);
        if (creditApplyList.size() > 0) {
            ruleInNextStep.setJobtitle(creditApplyList.get(0).getJobTitle());
        }

        ruleInNextStep = RuleUtils.afterFormat(ruleInNextStep);
        if ("-1".equals(ruleInNextStep.getState())) {
            ruleInNextStep.setState(UserConstants.BUSINESS_NORMAL);
        }


        if (ctcustomerCrsReport != null) {
//            ruleInNextStep = new RuleInNextParam().getCrsParams(ctcustomerCrsReport, ruleInNextStep);
//            return afterFormatRuleInNextStep(ruleInNextStep);

            RuleInNextStepCrs ruleInNextStepCrs = new RuleInNextStepCrs();
            BeanUtils.copyBeanProp(ruleInNextStepCrs, ruleInNextStep);

            return new CrsWriteFactory().setCrs(ruleInNextStepCrs, ctcustomerCrsReport);
        }

        if (ctcustomerXdsReport != null) {
            RuleInNextStepXds ruleInNextStepXds = new RuleInNextStepXds();
            BeanUtils.copyBeanProp(ruleInNextStepXds, ruleInNextStep);
            return new XdsWriteFactory().setXds(ruleInNextStepXds, ctcustomerXdsReport);
        }

        return ruleInNextStep;
    }

    private CreditAccount getCreditAccount(String customerNo) {
        CreditAccount creditAccount = new CreditAccount();
        creditAccount.setCustNo(customerNo);
        creditAccount.setState(UserConstants.BUSINESS_NORMAL);
        List<CreditAccount> selectCreditAccountList = creditAccountService.selectCreditAccountList(creditAccount);
        if (CollectionUtils.isEmpty(selectCreditAccountList)) {
            throw new BusinessException(RspEnmu.NO_RECORD);
        }
        return selectCreditAccountList.get(0);
    }

}
